package com.ctbri.vSearch.frame;

import com.ctbri.vSearch.util.PropUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by xuexi on 2017/4/24.
 */
public class RedisPool {

    private static JedisPool pool = null;
    private static final int MAX_IDLE = Integer.parseInt(PropUtil.getValue("redis.maxIdle"));
    private static final int MAX_TOTAL = Integer.parseInt(PropUtil.getValue("redis.maxTotal"));
    private static final int MAX_WAIT_MILLIS = Integer.parseInt(
            PropUtil.getValue("redis.connectionTimeOut"));
    private static final int TIMEOUT = Integer.parseInt(PropUtil.getValue("redis.connectionTimeOut"));
    private static final boolean TEST_ON_BORROW = true;
    //访问密码
    private static final String AUTH = PropUtil.getValue("redis.password");

    /**
     * 构建redis连接池
     *
     * @param ip
     * @param port
     * @return JedisPool
     */
    public static JedisPool getPool(String ip, int port) {

        if (pool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxIdle(MAX_IDLE);
            config.setMaxTotal(MAX_TOTAL);
            config.setMaxWaitMillis(MAX_WAIT_MILLIS);
            //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
            config.setTestOnBorrow(TEST_ON_BORROW);
            pool = new JedisPool(config, ip, port, TIMEOUT, AUTH );
        }
        return pool;
    }

    /**
     * 返还到连接池
     *
     * @param pool
     * @param client
     */
    public static void returnResource(JedisPool pool, Jedis client) {
        if (null != client) {
            //redis 2.90
            pool.returnResource(client);
        }
    }

    /**
     *
     * @param pool
     */
    public static void destory(JedisPool pool) {

        pool.destroy();

    }



}
